package com.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.MasterDao;
import com.example.data.request.ReqMasterList;
import com.example.data.response.RespMasterBaseInfo;
import com.example.entity.Master;
import com.example.service.MasterService;
import com.example.utils.BCrypt;
import com.example.utils.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:yanghua
 * Date:2023/10/7 8:30
 */
@Service
public class MasterServiceImpl extends ServiceImpl<MasterDao, Master> implements MasterService {
    @Resource
    private MasterDao masterDao;

    @Override
    public R addMaster(Master master) {
        String password = master.getPassword();
        master.setPassword(BCrypt.hashpw(password,BCrypt.gensalt())); // 密码加密
        int i = masterDao.insert(master);
        Map<String, Object> data = new HashMap<>();
        RespMasterBaseInfo resp = new RespMasterBaseInfo(master.getUsername(),master.getName());
        data.put("info", resp);
        return i == 1 ? R.ok(data,"添加管理员成功！") : R.error("添加失败！");
    }

    @Override
    public R deleteById(Long id) {
        // 应该判断是否是超级管理员登录才进行删除操作
        Integer i = masterDao.deleteMasterById(id);
        return i == 1 ? R.ok("删除成功！") : R.error("删除失败！");
    }

    @Override
    public R getMasterList(ReqMasterList reqMasterList) {
        reqMasterList.setPage((reqMasterList.getPage() - 1) * reqMasterList.getSize());
        List<Master> masterList = masterDao.getMasterList(reqMasterList);
        Integer number = masterDao.getMasterListNumber(reqMasterList);
        Map<String, Object> data = new HashMap<>();
        data.put("list", masterList);
        data.put("size", number);
        return R.ok(data, "查询成功");
    }

    @Override
    public R getMasterByUsername(String username) {
        Master m = masterDao.getMasterByUsername(username);
        Map<String, Object> data = new HashMap<>();
        data.put("info", m);
        return R.ok(data, "查询成功");
    }

    @Override
    public R updateMaster(Master master) {
        String password = master.getPassword();
        master.setPassword(BCrypt.hashpw(password,BCrypt.gensalt())); // 密码加密
        int i = masterDao.updateById(master);
        Master m = masterDao.getMasterById(master.getId());
        Map<String, Object> data = new HashMap<>();
        data.put("info", m);
        return i == 1 ? R.ok(data,"修改成功") : R.error("修改失败");
    }

    @Override
    public R getMasterById(Long id) {
        Master master = masterDao.getMasterById(id);
        Map<String, Object> data = new HashMap<>();
        data.put("info", master);
        return master == null ? R.error("查询失败") : R.ok(data, "查询成功");
    }
}
